<?php

class AccountsController extends AdminController
{
  public function init()
  {
    Yii::app()->user->loginUrl = '/admin/site/login';
  }

  public function filters()
  {
    return array(
            'accessControl', // perform access control for CRUD operations
    );
  }

  public function accessRules()
  {
    return array(
    array('allow', // allow all users to perform 'index' and 'view' actions
                                        'actions' => array('view', 'list', 'create', 'update', 'delete'),
                                        'roles' => array('member'),
    ),
    array('deny', // deny all users
                                        'users' => array('*'),
    ),
    );
  }

  public function actionView($id)
  {
    $this->render('view',array(
                        'model'=>$this->loadModel($id),
    ));
  }

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $model=new Accounts;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Accounts']))
    {
      $model->attributes=$_POST['Accounts'];
      if ($model->save()) {
        Yii::app()->user->setFlash('success', "Tạo account thành công");
        $this->redirect(array('list'));
      }
    }

    if (Yii::app()->request->getParam('memberId')) {
        $model->member_id = Yii::app()->request->getParam('memberId');
    }

    $this->render('create', array(
                        'model'=>$model,
                        'siteList' => $this->getSiteList(),
                        'statusList' => Constants::getAccountStatus(),
                        'adStatus' => Constants::getAdStatus(),
                        'gridStatus' => Constants::getGridStatus()));
  }

  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   * @param integer $id the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    $model=$this->loadModel($id);

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Accounts']))
    {
      $model->attributes=$_POST['Accounts'];
      if ($model->save()) {
        Yii::app()->user->setFlash('success', "Cập nhật account thành công");
        $this->redirect(array('list') + $_GET);
      }
    }

    $this->render('update',array(
                        'model'=>$model,
                        'siteList' => $this->getSiteList(),
                        'statusList' => Constants::getAccountStatus(),
                        'adStatus' => Constants::getAdStatus(),
                        'gridStatus' => Constants::getGridStatus()));
  }

  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   * @param integer $id the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    $model = $this->loadModel($id);
    $model->status = Constants::STATUS_REMOVE;
    $model->save();

    // if AJAX request (triggered by deletion via list grid view), we should not redirect the browser
    if (!isset($_GET['ajax'])) {
      Yii::app()->user->setFlash('success', "Xóa account thành công");
      $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('list'));
    }
  }


  /**
   * Manages all models.
   */
  public function actionList()
  {
    $criteria = new CDbCriteria();

    $criteria->addCondition('status !=:status', 'AND');
    $params = array(':status' => Constants::STATUS_REMOVE);
    $searchData = array();

    if (isset($_GET['memberId'])) {
        $_GET['Accounts']['member_id'] = $_GET['memberId']; 
    }

    if (isset($_GET['Accounts']) && sizeof($_GET['Accounts']) > 0) {
      $searchData = $_GET['Accounts'];

      foreach ($searchData as $key => $val) {
        if ($val != '') {
          $param = ':' . $key;
          $condtion = '';

          if ($key != 'create_date') {
            $condtion = $key . ' LIKE :' . $key . '';
            $params[$param] = '%' . $val . '%';
          } else {
            $condtion = $key . ' = :' . $key . '';
            $params[$param] = $val;
          }

          $criteria->addCondition($condtion, 'AND');
        }
      }
    }

    $criteria->params = $params;
    $count = Accounts::model()->count($criteria);

    $pages = new CPagination($count);

    // results per page
    $pages->pageSize = Constants::RECORD_OF_PAGE;
    $pages->applyLimit($criteria);

    $criteria->order = 'account_id DESC';
    $sort = new ExtSort('Accounts');
    $sort->applyOrder($criteria);

    $models = Accounts::model()->findAll($criteria);
    $searchModel=new Accounts('search');

    $crit = new CDbCriteria();
    $crit->addCondition('status != :status', 'AND');
    $crit->params = array(':status' => Constants::ACCOUNT_DELETE);
    $crit->order = 'sitename ASC';

    $siteList = Sites::model()->findAll($crit);

    if ($siteList) {
      $siteList = CHtml::listData($siteList, 'site_id', 'sitename');
    }

    $this->render('list',
    array('models' => $models,
            'pages' => $pages,
            'sort' => $sort,
            'searchModel' => $searchModel,
            'searchData' => $searchData,
            'statusList' => Constants::getAccountStatus(),
            'siteList' => $siteList,
            'adStatus' => Constants::getAdStatus(),
            'gridStatus' => Constants::getGridStatus()));

  }

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer $id the ID of the model to be loaded
   * @return Accounts the loaded model
   * @throws CHttpException
   */
  public function loadModel($id)
  {
    $model=Accounts::model()->findByPk($id);
    if($model===null)
    throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }

  /**
   * Performs the AJAX validation.
   * @param Accounts $model the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if(isset($_POST['ajax']) && $_POST['ajax']==='accounts-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
  
  private function getSiteList() {
      $crit = new CDbCriteria();
      $crit->addCondition('status != :status', 'AND');
      $crit->params = array(':status' => Constants::ACCOUNT_DELETE);
      $crit->order = 'sitename ASC';
      $siteList = Sites::model()->findAll($crit);
      
      if ($siteList) {
          $siteList = CHtml::listData($siteList, 'site_id', 'sitename');
      }

      return $siteList;
  }
}
